import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

const login = () =>
    import ('@/views/login')
const layout = () =>
    import ('@/views/layout')
const home = () =>
    import ('@/views/home')
const ask = () =>
    import ('@/views/ask')
const mine = () =>
    import ('@/views/mine')
const video = () =>
    import ('@/views/video')
const edit = () =>
    import ('@/views/mine/edit')
const search = () =>
    import ('@/views/search')
const article = () =>
    import ('@/views/article')
const result = () =>
    import ('@/views/search/result')
const chat = () =>
    import ('@/views/mine/chat')



Vue.use(VueRouter)

const routes = [
    { path: '/', redirect: '/layout/home' },
    { name: 'login', path: '/login', component: login },
    { name: 'chat', path: '/mine/chat', component: chat },
    { name: 'article', path: '/article', component: article },
    { name: 'edit', path: '/mine/edit', component: edit, meta: { needLogin: true } },
    {
        name: 'layout',
        path: '/layout',
        component: layout,
        children: [

            { name: 'home', path: 'home', component: home, meta: { needKeep: true } },
            { name: 'ask', path: 'ask', component: ask },
            { name: 'video', path: 'video', component: video },
            {
                name: 'mine',
                path: 'mine',
                component: mine,
                meta: {
                    // 标记这个路由为需要登录的的路口
                    needLogin: true
                }
            },
        ]
    },
    { name: 'search', path: '/search', component: search },
    { name: 'result', path: '/search/result', component: result }
]

const router = new VueRouter({
    routes
})
router.beforeEach((to, from, next) => {
    // console.log('to', to);
    if (to.meta.needLogin) {
        // console.log(to);
        if (store.state.tokenObj.token) {
            next()
        } else {
            Vue.prototype.$toast.fail('请先登录')
            next({
                name: 'login',
                query: {
                    back: to.path
                }
            })
        }
    } else {
        next()
    }

})
export default router